package com.gxuwz.attend.web.servlet.admin;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gxuwz.attend.context.AppContext;
import com.gxuwz.attend.entity.Instructor; // 引入Instructor实体类
import com.gxuwz.attend.service.admin.InstructorService; // 引入InstructorService
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.List;

@WebServlet("/admin/instructors") // 更新路径
public class InstructorServlet extends HttpServlet {

    private InstructorService instructorService; // 修改为InstructorService
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void init() throws ServletException {
        super.init();
        instructorService = AppContext.getBean(InstructorService.class); // 更新为InstructorService
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        String id = request.getParameter("id");
        int page = Integer.parseInt(request.getParameter("page"));
        int size = Integer.parseInt(request.getParameter("size"));
        int offset = (page - 1) * size;

        List<Instructor> instructors = instructorService.getAllInstructors(id, name, size, offset); // 调用InstructorService
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        String json = objectMapper.writeValueAsString(instructors);
        response.getWriter().write(json);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Instructor instructor = objectMapper.readValue(request.getInputStream(), Instructor.class); // 读取Instructor对象
        instructorService.addInstructor(instructor); // 调用InstructorService添加辅导员
        response.setStatus(HttpServletResponse.SC_CREATED); // 201 Created
    }

    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Instructor instructor = objectMapper.readValue(request.getInputStream(), Instructor.class); // 读取Instructor对象
        instructorService.updateInstructor(instructor); // 调用InstructorService更新辅导员
        response.setStatus(HttpServletResponse.SC_OK); // 200 OK
    }

    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String instID = request.getParameter("instID"); // 获取辅导员ID
        instructorService.deleteInstructor(instID); // 调用InstructorService删除辅导员
        response.setStatus(HttpServletResponse.SC_NO_CONTENT); // 204 No Content
    }
}
